<template>
  <div class="message-board-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>留言板</span>
      </div>
      
      <!-- 留言表单 -->
      <el-form :model="messageForm" :rules="messageRules" ref="messageFormRef" label-width="0px" class="message-form">
        <el-form-item prop="content">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入您的留言内容..."
            v-model="messageForm.content"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitMessage" :loading="submitLoading">发表留言</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider content-position="center">留言列表</el-divider>
      
      <!-- 留言列表 -->
      <div class="message-list" v-loading="loading">
        <div v-if="messageList.length > 0">
          <div v-for="item in messageList" :key="item.id" class="message-item">
            <div class="message-header">
              <div class="user-info">
                <i class="el-icon-user"></i>
                <span class="username">{{ item.username }}</span>
              </div>
              <span class="message-time">{{ formatDate(item.createTime) }}</span>
            </div>
            <div class="message-content">{{ item.content }}</div>
            <div v-if="item.reply" class="message-reply">
              <div class="reply-header">
                <i class="el-icon-s-custom"></i>
                <span class="admin-name">管理员回复</span>
                <span class="reply-time">{{ formatDate(item.replyTime) }}</span>
              </div>
              <div class="reply-content">{{ item.reply }}</div>
            </div>
            <el-divider></el-divider>
          </div>
          
          <!-- 分页 -->
          <el-pagination
            v-if="total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination"
          >
          </el-pagination>
        </div>
        
        <!-- 空数据提示 -->
        <el-empty v-else-if="!loading" description="暂无留言信息"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  name: 'MessageBoard',
  data() {
    return {
      // 留言表单
      messageForm: {
        content: ''
      },
      // 表单验证规则
      messageRules: {
        content: [
          { required: true, message: '请输入留言内容', trigger: 'blur' },
          { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      },
      // 留言列表
      messageList: [],
      // 加载状态
      loading: false,
      // 提交留言加载状态
      submitLoading: false,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    // 获取留言列表
    this.getMessageList()
  },
  methods: {
    // 获取留言列表
    async getMessageList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/message/list', {
          params: {
            page: this.currentPage,
            size: this.pageSize
          }
        })
        if (res.code === 200) {
          this.messageList = res.data.records || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '获取留言列表失败')
        }
      } catch (error) {
        console.error('获取留言列表失败', error)
        this.$message.error('获取留言列表失败，请稍后重试')
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },
    // 加载模拟数据
    loadMockData() {
      this.messageList = [
        {
          id: '1',
          userName: '张三',
          content: '请问《古代陶瓷艺术展》的展期是多久？是否有优惠票？',
          createTime: '2023-07-10 14:30:00',
          replyContent: '您好，《古代陶瓷艺术展》展期为7月1日至9月30日，学生和老年人凭证可享受半价优惠。',
          replyTime: '2023-07-10 15:45:00'
        },
        {
          id: '2',
          userName: '李四',
          content: '解说预约是否需要额外付费？一个解说员可以带多少人参观？',
          createTime: '2023-07-12 09:20:00',
          replyContent: '您好，解说预约不需要额外付费，一个解说员最多可带10人同时参观。',
          replyTime: '2023-07-12 10:15:00'
        },
        {
          id: '3',
          userName: '王五',
          content: '展览预约后如需取消，有时间限制吗？',
          createTime: '2023-07-15 16:40:00',
          replyContent: null,
          replyTime: null
        }
      ]
      this.total = this.messageList.length
    },
    // 提交留言
    submitMessage() {
      this.$refs.messageFormRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          // 发送留言请求
          const { data: res } = await this.$http.post('/message', {
            userId: this.$store.state.userInfo.id,
            content: this.messageForm.content
          })
          if (res.code === 200) {
            this.$message.success('留言发表成功')
            // 重置表单
            this.messageForm.content = ''
            this.$refs.messageFormRef.resetFields()
            // 刷新留言列表
            this.getMessageList()
          } else {
            this.$message.error(res.message || '留言发表失败')
          }
        } catch (error) {
          console.error('留言发表失败', error)
          this.$message.error('留言发表失败，请稍后重试')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.getMessageList()
    },
    // 处理每页条数变化
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.getMessageList()
    },
    // 格式化日期
    formatDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.message-board-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.message-form {
  margin-bottom: 20px;
}

.message-list {
  margin-top: 20px;
}

.message-item {
  margin-bottom: 15px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-left: 5px;
  font-weight: bold;
  color: #409EFF;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.message-reply {
  margin-top: 10px;
  margin-left: 20px;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.admin-name {
  margin-left: 5px;
  font-weight: bold;
  color: #67c23a;
}

.reply-time {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.reply-content {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  line-height: 1.6;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>